package com.onemile.app;

import java.util.ArrayList;
import java.util.Date;

import android.R.integer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.onemile.app.R.id;
import com.onemile.app.base.BaseUI;
import com.onemile.data.DXml;
import com.onemile.data.DXml.FieldList;
import com.onemile.entity.PubConst;
import com.onemile.entity.PubConst.ActivityCode;
import com.onemile.entity.Session;
import com.onemile.entity.model.EAddress;
import com.onemile.entity.model.ECoupon;
import com.onemile.entity.model.EOrder;
import com.onemile.entity.model.EOrderDetails;
import com.onemile.entity.model.EOrderDetailsAccessories;
import com.onemile.entity.model.EOrderDetailsAttribute;
import com.onemile.entity.model.EPromotions;
import com.onemile.entity.model.EShopInfo;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiData;
import com.onemile.utils.UtiDateTime;
import com.onemile.utils.UtiDialogsFactory;
import com.onemile.utils.UtiDialogsFactory.DialogCallBack;
import com.onemile.entity.MessageCode;

public class UISettlement extends BaseUI
{
   private TextView txtShopName;
   private TextView txtCommoditys;
   private TextView txtTime;
   private TextView txtAddress;
   private TextView txtPhone;
   private TextView txtConsignee;
   private TextView txtPromotion;
   private TextView txtCoupon;
   private TextView txtPrice;

   private TableRow trShopName;
   private TableRow trCommoditys;
   private TableRow trTime;
   private LinearLayout trAddress;
   private TableRow trAddress2;// 请选择一个地址

   private TableRow trPromotion;
   private TableRow trCoupon;

   private ImageView imgUpload;
   private ImageView imgEdit;
   private ImageView imgOK;

   private void InitControls()
   {
	  txtPrice = (TextView) findViewById(R.id.txtPrice_settle);
	  txtPrice.setText(String.valueOf(Session.getInstance().getTotalPrice()));
	  txtShopName = (TextView) findViewById(R.id.txtShopName_settle);
	  txtShopName.setText(Session.getInstance().getCurrentShop().getShopsName());
	  txtCommoditys = (TextView) findViewById(R.id.txtCommoditys_settle);
	  txtTime = (TextView) findViewById(R.id.txtDeliveryTime_settle);
	  Date time=new Date();
	  if(time.getMinutes()>=30)
	  {
		 txtTime.setText(String.format("%s:%s~%s:%s", String.valueOf(time.getHours()+1),"00",String.valueOf(time.getHours()+1),"30"));
	  }
	  else 
	  {
		 txtTime.setText(String.format("%s:%s~%s:%s", String.valueOf(time.getHours()),"30",String.valueOf(time.getHours()+1),"00"));
	  }
	  
	  txtAddress = (TextView) findViewById(R.id.txtAddress_settle);

	  txtPhone = (TextView) findViewById(R.id.txtMobile_settle);
	  txtPhone.setText(Session.getInstance().getUserInfo().getMobile());
	  txtConsignee = (TextView) findViewById(R.id.txtConsginee_settle);
	  txtConsignee.setText(Session.getInstance().getUserInfo().getFullName());
	  txtPromotion = (TextView) findViewById(R.id.txtPromotion_settle);
	  txtCoupon = (TextView) findViewById(R.id.txtVoucher_settle);

	  trShopName = (TableRow) findViewById(R.id.trShopName_settle);

	  trCommoditys = (TableRow) findViewById(R.id.trCommoditys_settle);// 商品详情
	  trCommoditys.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Intent intent = new Intent();
			intent.setClass(UISettlement.this, UISettleCommodityList.class);
			startActivity(intent);

		 }
	  });
	  trTime = (TableRow) findViewById(R.id.trTime_settle);// 送货时间
	  trTime.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			final ArrayList<String> list = new ArrayList<String>();
			if (Session.getInstance().getCurrentShop() != null)
			{
			   int openHour = Integer.valueOf(Session.getInstance().getCurrentShop().getOpeningTime().split(":")[0]);
			   int openMin = Integer.valueOf(Session.getInstance().getCurrentShop().getOpeningTime().split(":")[1]);
			   int closeHour = Integer.valueOf(Session.getInstance().getCurrentShop().getClosingTime().split(":")[0]);
			   int closeMin = Integer.valueOf(Session.getInstance().getCurrentShop().getClosingTime().split(":")[1]);

			   while (true)
			   {
				  if (openMin == 0)
				  {
					 list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour), "00", String.valueOf(openHour), "30"));
					 list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour), "30", String.valueOf(openHour + 1), "00"));
					 openHour++;
					 if (openHour == closeHour)
					 {
						if (closeMin == 0)
						{
						   break;
						}
						else if (closeMin > 0 && closeMin <= 30)
						{
						   break;
						}
						else if (closeMin > 30)
						{
						   list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour), "00", String.valueOf(openHour), "30"));
						   break;
						}
					 }
				  }
				  else if (openMin > 0 && openMin <= 30)
				  {
					 list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour), "30", String.valueOf(openHour + 1), "00"));
					 list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour + 1), "00", String.valueOf(openHour + 1), "30"));
					 openHour++;
					 if (openHour == closeHour)
					 {
						if (closeMin == 0)
						{
						   break;
						}
						else if (closeMin > 0 && closeMin <= 30)
						{
						   break;
						}
						else if (closeMin > 30)
						{
						   list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour), "00", String.valueOf(openHour), "30"));
						   break;
						}
					 }
				  }
				  else if (openMin > 30)
				  {
					 list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour + 1), "00", String.valueOf(openHour + 1), "30"));
					 list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour + 1), "30", String.valueOf(openHour + 2), "00"));
					 openHour++;
					 if (openHour == closeHour)
					 {
						if (closeMin == 0)
						{
						   break;
						}
						else if (closeMin > 0 && closeMin <= 30)
						{
						   break;
						}
						else if (closeMin > 30)
						{
						   list.add(String.format("%s:%s~%s:%s", String.valueOf(openHour), "00", String.valueOf(openHour), "30"));
						   break;
						}
					 }
				  }
			   }
			}

			UtiDialogsFactory.getInstance().ShowSingleSelectItemDialog(UISettlement.this, list, null, new UtiDialogsFactory.DialogCallBack()
			{
			   @Override
			   public void SingleSelectDialogItemClick(ListView listView, View currentView, int position)
			   {
				  txtTime.setText(list.get(position));
			   }

			   @Override
			   public void MultiSelectDialogOKClick(ListView listView, ArrayList<Integer> selectList, int count)
			   {}
			});
		 }
	  });
	  trAddress = (LinearLayout) findViewById(R.id.trAddress_settle);// 地址
	  trAddress.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Intent intent = new Intent();
			intent.setClass(UISettlement.this, UISettlementAddress.class);
			intent.putExtra(PubConst.Intent_Key.IS_NEW_ADDRESS, false);
			Session.getInstance().setAddressCache((EAddress) txtPhone.getTag());
			startActivityForResult(intent, PubConst.ActivityCode.SETTLE_ADDRESS);
		 }
	  });
	  trAddress2 = (TableRow) findViewById(R.id.trAddress2_settle);// 请选择地址
	  trAddress2.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			Intent intent = new Intent();
			intent.setClass(UISettlement.this, UISettlementAddress.class);
			startActivityForResult(intent, PubConst.ActivityCode.SETTLE_ADDRESS);
		 }
	  });

	  trPromotion = (TableRow) findViewById(R.id.trPromotion_settle);// 商家优惠
	  trPromotion.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			executeAsyncTask(PubConst.TaskName.SETTLE_PROMOTIONS);
		 }
	  });
	  trCoupon = (TableRow) findViewById(R.id.trVoucher_settle);// 抵用券
	  trCoupon.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			executeAsyncTask(PubConst.TaskName.SETTLE_COUPON);
		 }
	  });

	  imgOK = (ImageView) findViewById(R.id.imgOK_settle);
	  imgOK.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			// TODO Auto-generated method stub

		 }
	  });
	  imgUpload = (ImageView) findViewById(R.id.imgUpload_settle);
	  imgUpload.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {

			executeAsyncTask(PubConst.TaskName.SETTLEMENT);

		 }
	  });
   }

   @Override
   protected void onResume()
   {
	  super.onResume();

   }

   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  InitControls();

   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.settlement;
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
	  topTxt.setText(getString(R.string.title_ordersettle));
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data)
   {
	  if (requestCode == PubConst.ActivityCode.SETTLE_ADDRESS)
	  {
		 if (resultCode == Activity.RESULT_OK)
		 {
			trAddress.setVisibility(View.VISIBLE);
			trAddress2.setVisibility(View.GONE);

			txtPhone.setTag(Session.getInstance().getAddressCache());

			txtConsignee.setText(Session.getInstance().getAddressCache().getConsignee());
			txtPhone.setText(Session.getInstance().getAddressCache().getMobile());
			txtAddress.setText(Session.getInstance().getAddressCache().getAddress());

			Session.getInstance().CleanAddressCache();
		 }
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if (taskName.equals(PubConst.TaskName.SETTLEMENT))
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UISettlement.this, getString(R.string.dialog_uploading));
	  }
	  if (taskName.equals(PubConst.TaskName.SETTLE_PROMOTIONS) || taskName.equals(PubConst.TaskName.SETTLE_COUPON))
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UISettlement.this, getString(R.string.dialog_loading));
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if (taskName.equals(PubConst.TaskName.SETTLEMENT))
	  {
		 try
		 {

			EPromotions promotions = (EPromotions) txtPromotion.getTag();

			EOrder order = new EOrder();
			order.setEarliestTime(txtTime.getText().toString().split("~")[0]);
			order.setLatestTime(txtTime.getText().toString().split("~")[1]);
			order.setFreight(Float.valueOf(Session.getInstance().getCurrentShop().getFreight()));
			order.setOrderAddress(txtAddress.getText().toString());
			order.setOrderMobile(txtPhone.getText().toString());
			order.setOrderName(txtConsignee.getText().toString());
			order.setOrderRemarks("");
			order.setShopId(Session.getInstance().getCurrentShop().getShopsId());
			order.setUserId(Session.getInstance().getUserInfo().getUserId());
			order.setRec_CreateBy(Session.getInstance().getUserInfo().getUserName());
			order.setRec_ModifyBy(Session.getInstance().getUserInfo().getUserName());

			// 添加具体商品列表
			ArrayList<EOrderDetails> listOD = new ArrayList<EOrderDetails>();
			EOrderDetails details = null;
			int size = Session.getInstance().getCommodityList().size();
			float actualPrice = 0;
			for (int i = 0; i < size; i++)
			{
			   details = new EOrderDetails();
			   details.setCommodityId(Session.getInstance().getCommodityList().get(i).getCommodityId());
			   details.setCommodityName(Session.getInstance().getCommodityList().get(i).getCommodityName());
			   details.setAmount(Session.getInstance().getCommodityList().get(i).getCount());// 数量
			   details.setUnitPrice(Session.getInstance().getCommodityList().get(i).getSpecification().getPrice());// 该规格下的商品单价
			   details.setCommodityPriceId(Session.getInstance().getCommodityList().get(i).getSpecification().getCommodityPriceId());

			   // 添加附件列表==============================
			   StringBuffer sbAccessories = new StringBuffer();
			   ArrayList<EOrderDetailsAccessories> listODC = new ArrayList<EOrderDetailsAccessories>();
			   EOrderDetailsAccessories accessories = null;
			   int size2 = Session.getInstance().getCommodityList().get(i).getCommodityAccessoriesList().size();
			   float accessoriesPrice = 0;
			   for (int j = 0; j < size2; j++)
			   {
				  accessories = new EOrderDetailsAccessories();
				  accessories.setCommodityAccessoriesId(Session.getInstance().getCommodityList().get(i).getCommodityAccessoriesList().get(j).getCommodityAccessoriesId());
				  sbAccessories.append(Session.getInstance().getCommodityList().get(i).getCommodityAccessoriesList().get(j).getCommodityAccessoriesName());
				  sbAccessories.append(",");
				  accessoriesPrice += Float.valueOf(Session.getInstance().getCommodityList().get(i).getCommodityAccessoriesList().get(j).getCommodityAccessoriesPrice());
				  listODC.add(accessories);
			   }
			   details.setCommodityAccessoriesName(sbAccessories.substring(0, sbAccessories.length() - 1));
			   details.setOrderDetailsAccessoriesList(listODC);

			   // 添加属性列表=================================
			   StringBuffer sbAttribute = new StringBuffer();
			   ArrayList<EOrderDetailsAttribute> listODA = new ArrayList<EOrderDetailsAttribute>();
			   EOrderDetailsAttribute attribute = null;
			   int size3 = Session.getInstance().getCommodityList().get(i).getAttributeDetailsList().size();
			   for (int k = 0; k < size3; k++)
			   {
				  attribute = new EOrderDetailsAttribute();
				  attribute.setAttributeDetailsId(Session.getInstance().getCommodityList().get(i).getAttributeDetailsList().get(k).getAttributeDetailsId());
				  sbAttribute.append(Session.getInstance().getCommodityList().get(i).getAttributeDetailsList().get(k).getAttributeDetailsName());
				  sbAttribute.append(",");
				  listODA.add(attribute);
			   }
			   details.setAttributeDetailsName(sbAttribute.substring(0, sbAttribute.length() - 1));
			   details.setOrderDetailsAttributeList(listODA);

			   // 计算每个商品的折扣
			   if (promotions != null && promotions.getPromotionsType() == 2)
			   {
				  details.setPromotionsId(promotions.getPromotionsId());
				  details.setDiscount(promotions.getDiscount());
				  details.setDiscountPrice(details.getUnitPrice() * details.getDiscount());
				  details.setActualTotalPrice((details.getDiscountPrice() + accessoriesPrice) * details.getAmount());
			   }
			   else
			   {
				  details.setActualTotalPrice((details.getUnitPrice() + accessoriesPrice) * details.getAmount());
			   }

			   actualPrice += details.getActualTotalPrice();// 累加所有商品的实际总价（包括折扣，折扣为0时跟总价相等）
			   details.setTotalPrice((details.getUnitPrice() + accessoriesPrice) * details.getAmount());// 原来的总价格（不包括折扣）
			   listOD.add(details);
			}

			order.setOrderDetailsList(listOD);

			// 计算整个订单的折扣
			if (promotions != null)
			{
			   order.setPromotionsId(promotions.getPromotionsId());
			   switch (promotions.getPromotionsType())
			   {
				  case 1:
					 actualPrice = actualPrice * promotions.getDiscount();
					 break;
				  case 3:
					 actualPrice = actualPrice - promotions.getOffsetPrice();
					 break;
				  case 4:
					 actualPrice = actualPrice - promotions.getOffsetPrice();
					 break;
			   }
			}
			// 计算抵用券所减去的金额
			ECoupon coupon = (ECoupon) txtCoupon.getTag();
			if (coupon != null)
			{
			   order.setCouponId(coupon.getCouponId());
			   actualPrice = actualPrice - coupon.getCouponPrice();
			}

			// 添加运费
			actualPrice += order.getFreight();
			actualPrice=UtiData.ToDecimal(actualPrice, 1);
			order.setTotalPrice(actualPrice);

			return NetClient.InsertNewOrder(order);
		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   Log.e("ERROR", "UISettlement_onAsyncTaskInBackground_InsertNewOrder(taskName, params) ", e);
			}
		 }
	  }
	  if (taskName != null && taskName.equals(PubConst.TaskName.SETTLE_PROMOTIONS))
	  {
		 try
		 {
			return NetClient.GetPromotions(Session.getInstance().getCurrentShop().getShopsId());
		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   Log.e("ERROR", "UISettlement_onAsyncTaskInBackground_GetPromotions(taskName, params) ", e);
			}
		 }
	  }
	  if (taskName != null && taskName.equals(PubConst.TaskName.SETTLE_COUPON))
	  {
		 try
		 {
			return NetClient.GetCoupons(Session.getInstance().getCurrentShop().getShopsId(), Session.getInstance().getUserInfo().getUserId());
		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   Log.e("ERROR", "UISettlement_onAsyncTaskInBackground(taskName, params) ", e);
			}
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  if (taskName.equals(PubConst.TaskName.SETTLEMENT))
	  {
		 try
		 {
			UtiDialogsFactory.getInstance().DismissLoadingDialog();
			if (result != null)
			{
			   DXml data = (DXml) result;
			   if (data.getHead().GetFieldValue("RspCode").equals(MessageCode.Success.Code))
			   {
				  UtiDialogsFactory.getInstance().ShowOKAlertDialog(UISettlement.this, getString(R.string.dialog_tips), getString(R.string.dialog_uploading_success),
						new DialogInterface.OnClickListener()
						{
						   @Override
						   public void onClick(DialogInterface dialog, int which)
						   {		
							  Session.getInstance().CleanCommodityList();//清楚购物车
							  Intent intent = new Intent();
							  intent.setClass(UISettlement.this, UIOrderList.class);
							  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							  startActivity(intent);
							  finish();
						   }
						});
			   }
			   else
			   {
				  UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlement.this, data.getHead().GetFieldValue("RspMsg"));
			   }
			}
			else
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlement.this, getString(R.string.dialog_server_failed));
			}

		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   UtiDialogsFactory.getInstance().DismissLoadingDialog();
			   Log.e("ERROR", "UISettlement_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
			}
		 }
	  }
	  if (taskName.equals(PubConst.TaskName.SETTLE_PROMOTIONS))
	  {
		 try
		 {
			UtiDialogsFactory.getInstance().DismissLoadingDialog();
			if (result != null)
			{
			   DXml data = (DXml) result;
			   if (data.getHead().GetFieldValue("RspCode").equals(MessageCode.Success.Code))
			   {
				  ArrayList<EPromotions> list = new ArrayList<EPromotions>();
				  EPromotions prom = null;
				  int size = data.getBody().getChilds().length;
				  for (int i = 0; i < size; i++)
				  {
					 FieldList fieldList = data.getBody().GetFieldList(i);

					 prom = new EPromotions();
					 prom.setPromotionsId(fieldList.GetFieldValue("PromotionsId"));
					 prom.setPromotionsTitle(fieldList.GetFieldValue("PromotionsTitle"));
					 prom.setPromotionsType(fieldList.GetFieldInt32("PromotionsType"));
					 prom.setCommodityId(fieldList.GetFieldValue("CommodityId"));
					 prom.setConditionPrice(fieldList.GetFieldFloat("ConditionPrice"));
					 prom.setOffsetPrice(fieldList.GetFieldFloat("OffsetPrice"));
					 prom.setDiscount(fieldList.GetFieldFloat("Discount"));
					 prom.setShopsId(fieldList.GetFieldValue("ShopsId"));
					 prom.setStartDate(fieldList.GetFieldValue("StartDate"));
					 prom.setEndDate(fieldList.GetFieldValue("EndDate"));

					 if (prom.getPromotionsType() != 3)
					 {
						list.add(prom);
					 }
					 else
					 // 满减
					 {
						if (Session.getInstance().getTotalPrice() >= prom.getConditionPrice())
						{
						   list.add(prom);
						}
					 }
				  }
				  list.add(new EPromotions(getString(R.string.all_donnot_use)));// 添加一个不使用优惠券的选项

				  UtiDialogsFactory.getInstance().ShowSingleSelectItemDialog(UISettlement.this, list, getString(R.string.settle_select_promotion), new DialogCallBack()
				  {
					 @Override
					 public void SingleSelectDialogItemClick(ListView listView, View currentView, int position)
					 {
						String title = ((EPromotions) listView.getAdapter().getItem(position)).getPromotionsTitle();
						if (title.equals(getString(R.string.all_donnot_use)))
						{
						   txtPromotion.setText(getString(R.string.all_none));
						   txtPromotion.setTag(null);
						}
						else
						{
						   txtPromotion.setText(title);
						   txtPromotion.setTag(listView.getAdapter().getItem(position));
						}
						CalculatePrice();
					 }

					 @Override
					 public void MultiSelectDialogOKClick(ListView listView, ArrayList<Integer> selectList, int count)
					 {
					 }
				  });
			   }
			   else
			   {
				  UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlement.this, data.getHead().GetFieldValue("RspMsg"));
			   }
			}
			else
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlement.this, getString(R.string.dialog_server_failed));
			}
		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   Log.e("ERROR", "UISettlement_onAsyncTaskEnd_SETTLE_PROMOTIONS(taskId, taskName, params, result) ", e);
			}
		 }
	  }
	  if (taskName.equals(PubConst.TaskName.SETTLE_COUPON))
	  {
		 try
		 {
			UtiDialogsFactory.getInstance().DismissLoadingDialog();
			if (result != null)
			{
			   DXml data = (DXml) result;
			   if (data.getHead().GetFieldValue("RspCode").equals(MessageCode.Success.Code))
			   {
				  ArrayList<ECoupon> list = new ArrayList<ECoupon>();
				  ECoupon coupon = null;
				  int size = data.getBody().getChilds().length;
				  for (int i = 0; i < size; i++)
				  {
					 FieldList fieldList = data.getBody().GetFieldList(i);

					 coupon = new ECoupon();
					 coupon.setCouponId(fieldList.GetFieldValue("CouponId"));
					 coupon.setCouponName(fieldList.GetFieldValue("CouponName"));
					 coupon.setCouponPrice(fieldList.GetFieldFloat("CouponPrice"));
					 coupon.setUsedTime(fieldList.GetFieldValue("UsedTime"));
					 coupon.setIsUsed(fieldList.GetFieldInt32("IsUsed"));
					 coupon.setStartDate(fieldList.GetFieldValue("StartDate"));
					 coupon.setEndDate(fieldList.GetFieldValue("EndDate"));

					 list.add(coupon);
				  }
				  list.add(new ECoupon(getString(R.string.all_donnot_use)));// 添加一个不使用优惠券的选项

				  UtiDialogsFactory.getInstance().ShowSingleSelectItemDialog(UISettlement.this, list, getString(R.string.settle_select_coupon), new DialogCallBack()
				  {
					 @Override
					 public void SingleSelectDialogItemClick(ListView listView, View currentView, int position)
					 {
						String title = ((ECoupon) listView.getAdapter().getItem(position)).getCouponName();
						if (title.equals(getString(R.string.all_donnot_use)))
						{
						   txtCoupon.setText(getString(R.string.all_none));
						   txtCoupon.setTag(null);
						}
						else
						{
						   txtCoupon.setText(title);
						   txtCoupon.setTag(listView.getAdapter().getItem(position));
						}
						CalculatePrice();
					 }

					 @Override
					 public void MultiSelectDialogOKClick(ListView listView, ArrayList<Integer> selectList, int count)
					 {
					 }
				  });
			   }
			   else
			   {
				  UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlement.this, data.getHead().GetFieldValue("RspMsg"));
			   }
			}
			else
			{
			   UtiDialogsFactory.getInstance().ShowToastInfoShort(UISettlement.this, getString(R.string.dialog_server_failed));
			}
		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   Log.e("ERROR", "UISettlement_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
			}
		 }
	  }
   }

   private void CalculatePrice()
   {
	  if (txtPromotion.getTag() != null && txtCoupon.getTag() == null)
	  {
		 int type = ((EPromotions) txtPromotion.getTag()).getPromotionsType();
		 switch (type)
		 {
			case 1:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(1, ((EPromotions) txtPromotion.getTag()).getDiscount()),1)));
			   break;
			case 2:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(2, ((EPromotions) txtPromotion.getTag()).getDiscount()),1)));
			   break;
			case 3:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(((EPromotions) txtPromotion.getTag()).getOffsetPrice()),1)));
			   break;
			case 4:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(((EPromotions) txtPromotion.getTag()).getOffsetPrice()),1)));
			   break;
		 }
	  }
	  else if (txtPromotion.getTag() == null && txtCoupon.getTag() != null)
	  {
		 txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice() - ((ECoupon) txtCoupon.getTag()).getCouponPrice(),1)));
	  }
	  else if (txtPromotion.getTag() != null && txtCoupon.getTag() != null)
	  {
		 int type = ((EPromotions) txtPromotion.getTag()).getPromotionsType();
		 switch (type)
		 {
			case 1:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(1, ((EPromotions) txtPromotion.getTag()).getDiscount()) - ((ECoupon) txtCoupon.getTag()).getCouponPrice(),1)));
			   break;
			case 2:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(2, ((EPromotions) txtPromotion.getTag()).getDiscount()) - ((ECoupon) txtCoupon.getTag()).getCouponPrice(),1)));
			   break;
			case 3:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(((EPromotions) txtPromotion.getTag()).getOffsetPrice()) - ((ECoupon) txtCoupon.getTag()).getCouponPrice(),1)));
			   break;
			case 4:
			   txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(((EPromotions) txtPromotion.getTag()).getOffsetPrice()) - ((ECoupon) txtCoupon.getTag()).getCouponPrice(),1)));
			   break;
		 }
	  }
	  else
	  {
		 txtPrice.setText(String.valueOf(UtiData.ToDecimal(Session.getInstance().getTotalPrice(),1)));
	  }
   }
}
